package com.hankol.material.fragment

import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseLazyFragment
import com.baselibrary.bean.download.DownloadInfo
import com.baselibrary.db.DBManager
import com.baselibrary.manager.LoadingManager
import com.baselibrary.utils.EventBusUtils
import com.baselibrary.utils.FileUtils
import com.baselibrary.utils.SpUtils
import com.baselibrary.utils.ToastUtils
import com.hankol.material.R
import com.hankol.material.adapter.TabDownloadCompleteAdapter
import com.hankol.material.databinding.FragmentDownloadCompleteBinding
import com.hankol.material.help.PopUtils
import com.hankol.material.limit.DownloadLimitManager
import com.hankol.material.viewmodel.MaterialBaseViewModel
import com.hankol.material.viewmodel.TabDownloadCompleteViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File

/**Tab--下载完成列表
 * @author: merbng
 * @time: 2021/10/15 10:36
 * @description:
 */
class DownloadCompleteFragment : BaseLazyFragment(true) {

    lateinit var binding: FragmentDownloadCompleteBinding
    private var viewModel: TabDownloadCompleteViewModel? = null
    val adapter: TabDownloadCompleteAdapter by lazy { TabDownloadCompleteAdapter() }
    private var hasnext: Boolean = false

    companion object {
        fun newInstance(): DownloadCompleteFragment {
            return DownloadCompleteFragment()
        }
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }

        binding = getDataBinding()
        viewModel = getFragmentViewModelProvider(this).get(TabDownloadCompleteViewModel::class.java)
        binding.rvOrder.setLayoutManager(LinearLayoutManager(activity))
        binding.rvOrder.setAdapter(adapter)
        adapter.setOnItemClickListener { adapter, view, position ->
            //            OpenWithWPSUtil.openWithWPS(context, adapter.data[position] as File, false)
            openDetail((adapter.data[position] as DownloadInfo).path)
        }
        adapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.img_del -> {
                    PopUtils.showRightLeftDialog(attachActivity, "确认删除下载信息", object : MaterialBaseViewModel.IRightLeftCallBack {
                        override fun leftClick() {

                        }

                        override fun rightClick() {
                            ToastUtils.showShort(attachActivity, "文件已删除")
                            DownloadLimitManager.getInstance().cancelDownload(adapter.data[position] as DownloadInfo)
                            EventBusUtils.sendNotify(MessageBus.msgId_del_material_file)
                            showEmpty(adapter.data.size)
                        }
                    })
                }
                R.id.tv_open -> {
                    if ((adapter.data[position] as DownloadInfo).path != null) {
                        openDetail((adapter.data[position] as DownloadInfo).path)
                    }
                }
            }
        }
//        binding.sv.setHeader(SpringViewNewHeader(activity))
//        binding.sv.setFooter(SpringViewNewFooter(activity))
//        binding.sv.setType(SpringView.Type.FOLLOW)
//        binding.sv.setListener(object : SpringView.OnFreshListener {
//            override fun onRefresh() {
//                EventBusUtils.sendNotify(MessageBus.msgId_refresh_capacity)
//                loadData()
//            }
//
//            override fun onLoadmore() {
//                if (hasnext) {
//                    loadData()
//                } else {
//                    binding.sv.onFinishFreshAndLoad()
//                }
//            }
//        })
        viewModel?.dataListLD?.observe(this, Observer {
            if (it != null) {
                adapter.setNewData(it)
                showEmpty(it.size)
            } else {
                showEmpty(0)
            }
//            binding.sv.onFinishFreshAndLoad()
            LoadingManager.hideLoadingDialog(activity)
        })
    }

    //打开文件详情 判断文件是否存在
    private fun openDetail(path: String) {
        path.let {
            if (FileUtils.fileIsExists(it)) {
                DownloadLimitManager.openFile(attachActivity, File(path))
            } else {
                ToastUtils.showShort(attachActivity, "文件已删除")
            }
        }
    }

    private fun showEmpty(size: Int) {
        binding.tvEmpty.visibility = if (size > 0) View.GONE else View.VISIBLE
    }

    override fun lazyLoadData() {
        LoadingManager.showLoadingDialog(activity)
        loadData()
    }

    fun loadData() {
        viewModel?.getAlwayDownloadList()
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_download_complete
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }

    val userIds: Int by lazy { SpUtils.getInstance().userId }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun update(info: DownloadInfo) {
        if (DownloadInfo.DOWNLOAD_CANCEL.equals(info.getDownloadStatus())) {
            val it = adapter.data.iterator()
            while (it.hasNext()) {
                val x = it.next()
                if (info.url.equals(x.url)) {
                    it.remove()
                    DBManager.getInstance().deleteDownload(userIds, info.url)
                    adapter.notifyDataSetChanged()
                }
            }
        } else if (DownloadInfo.DOWNLOAD_OVER.equals(info.getDownloadStatus())) {
            //下载完成  刷新当前列表
            loadData()
        }
    }
}

